﻿<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-tabs v-model="activeTab">
			<el-tab-pane label="基础信息" name="main">
				<el-card shadow="hover" class="layout-padding-auto create-form">
					<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>单据信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_BillCode_FormItem" prop="Entity.BillCode">
										<template #label>
											<WtmLabelTooltip label="单据编号" tooltip="单据编号" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.BillCode" disabled clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_BillStatus_FormItem" prop="Entity.BillStatus">
										<template #label>
											<WtmLabelTooltip label="单据状态" tooltip="单据状态" />
										</template>
										<el-select v-model="stateData.vmModel.Entity.BillStatus" disabled clearable class="width100">
											<el-option v-for="item in BILL_STATUS_OPTIONS" :key="item" :value="item" :label="item"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_WorkflowStatus_FormItem" prop="Entity.WorkflowStatus">
										<template #label>
											<WtmLabelTooltip label="工作流状态" tooltip="工作流状态" />
										</template>
										<el-select v-model="stateData.vmModel.Entity.WorkflowStatus" disabled clearable class="width100">
											<el-option v-for="item in WORKFLOW_STATUS_OPTIONS" :key="item" :value="item" :label="item"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_Remark_FormItem" prop="Entity.Remark">
										<template #label>
											<WtmLabelTooltip label="备注" tooltip="备注" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.Remark" disabled clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
							</el-row>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>退休信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_PersonId_FormItem" prop="Entity.PersonId">
										<template #label>
											<WtmLabelTooltip label="退休员工" tooltip="选择申请退休的员工" />
										</template>
										<WtmPersonSelector
											v-model="stateData.vmModel.Entity.PersonId"
											:prefill-person="{
												ID: stateData.vmModel.Entity.PersonId,
												Name: stateData.vmModel.Entity.Name,
												StaffNo: stateData.vmModel.Entity.StaffNo,
											}"
											:disabled="true"
											:clearable="false"
										/>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_StaffNo_FormItem" prop="Entity.StaffNo">
										<template #label>
											<WtmLabelTooltip label="员工工号" tooltip="员工工号" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.StaffNo" disabled clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_Name_FormItem" prop="Entity.Name">
										<template #label>
											<WtmLabelTooltip label="员工姓名" tooltip="员工姓名" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.Name" disabled clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_RetireDate_FormItem" prop="Entity.RetireDate">
										<template #label>
											<WtmLabelTooltip label="退休日期" tooltip="退休日期" />
										</template>
										<el-date-picker v-model="stateData.vmModel.Entity.RetireDate" disabled clearable class="width100"></el-date-picker>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_ResignType_FormItem" prop="Entity.ResignType">
										<template #label>
											<WtmLabelTooltip label="离职类型" tooltip="离职类型" />
										</template>
										<el-select v-model="stateData.vmModel.Entity.ResignType" disabled clearable class="width100">
											<el-option key="正常退休" value="正常退休" label="正常退休"></el-option>
											<el-option key="提前退休" value="提前退休" label="提前退休"></el-option>
											<el-option key="内退" value="内退" label="内退"></el-option>
											<el-option key="病退" value="病退" label="病退"></el-option>
											<el-option key="特殊工种退休" value="特殊工种退休" label="特殊工种退休"></el-option>
											<el-option key="因公伤残退休" value="因公伤残退休" label="因公伤残退休"></el-option>
											<el-option key="困难企业职工退休" value="困难企业职工退休" label="困难企业职工退休"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="24" class="mb20">
									<el-form-item ref="Entity_Describe_FormItem" prop="Entity.Describe">
										<template #label>
											<WtmLabelTooltip label="退休说明" tooltip="退休说明" />
										</template>
										<el-input type="textarea" v-model="stateData.vmModel.Entity.Describe" disabled clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
							</el-row>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>工作信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<WtmOrgSelector v-model="stateData.vmModel.Entity.OrgId" label="公司" :disabled="true" :auth="false" placeholder="选取人员后带入" />
								</el-col>

								<el-col :xs="24" :lg="12" class="mb20">
									<WtmDeptSelector v-model:model-value="stateData.vmModel.Entity.GroupId" label="所属部门" :disabled="true" :auth="false" />
								</el-col>
							</el-row>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>流程信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_Approver_FormItem" prop="Entity.Approver">
										<template #label>
											<WtmLabelTooltip label="审批人" tooltip="流程审批人" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.Approver" disabled clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_ApprovalTime_FormItem" prop="Entity.ApprovalTime">
										<template #label>
											<WtmLabelTooltip label="审批时间" tooltip="流程审批时间" />
										</template>
										<el-date-picker v-model="stateData.vmModel.Entity.ApprovalTime" disabled clearable class="width100"></el-date-picker>
									</el-form-item>
								</el-col>
							</el-row>
						</div>
					</el-form>
				</el-card>
			</el-tab-pane>
			<el-tab-pane label="审批信息" key="审批信息">
				<WtmWorkflowTimeline entityType="HengTong.Model.Db.Bill.SysHrRetireRequestBill" :entityId="stateData.vmModel.Entity.ID" />
			</el-tab-pane>
		</el-tabs>
	</div>
</template>

<script setup lang="ts" name="message._system.common.vm.details;false">
import { reactive, ref, getCurrentInstance, onMounted, nextTick, computed, type ComponentInternalInstance } from 'vue';
import { ElMessage } from 'element-plus';
import { SysHrRetireRequestBillApi as api } from '/@/views/hr/syshrretirerequestbill/api';
import other from '/@/utils/other';
import { useRouter } from 'vue-router';
import { ISysHrRetireRequestBillVm } from '/@/views/hr/syshrretirerequestbill/api/interface';
import { IViewModel } from '/@/types/common';
import ApproveReasonDialog from '/@/components/approveReason/index.vue';

/**
 * ===== 常量定义区域 =====
 * 统一管理业务常量，便于维护和复用
 */

/** 单据状态选项 */
const BILL_STATUS_OPTIONS = ['草稿', '正文'] as const;

/** 工作流状态枚举 */
const WORKFLOW_STATUS = {
	PENDING: '待提交', // 初始状态，等待提交
	SUBMITTING: '提交中', // 正在提交流程
	IN_AUDIT: '审核中', // 审批流程中
	COMPLETED: '已完成', // 流程完成
	CANCELLED: '已取消', // 流程取消
} as const;

/** 从 WORKFLOW_STATUS 对象生成选项数组 */
const WORKFLOW_STATUS_OPTIONS = Object.values(WORKFLOW_STATUS);

/** 审批操作类型 */
const ACTIONS = {
	AGREE: '同意', // 同意审批
	REJECT: '拒绝', // 拒绝审批
} as const;

/** 按钮文本配置 */
const BUTTON_TEXTS = {
	AGREE: ACTIONS.AGREE, // 同意按钮文本
	REJECT: ACTIONS.REJECT, // 拒绝按钮文本
	CLOSE: '关闭', // 关闭按钮文本
} as const;

/**
 * ===== 组件实例和基础配置 =====
 */

/** 组件实例，用于访问组件上下文 */
const ci = getCurrentInstance() as ComponentInternalInstance;

/** 页面加载状态控制 */
const loading = ref(false);

/** 表单引用 */
const formRef = ref();

/** 当前激活的标签页 */
const activeTab = ref('main');

/**
 * ===== 响应式状态数据 =====
 */

/** 详情页面数据模型 */
const stateData = reactive<IViewModel<ISysHrRetireRequestBillVm>>({
	vmModel: {
		Entity: {
			ID: null, // 记录ID
			PersonId: null, // 员工ID
			StaffNo: null, // 员工工号
			Name: null, // 员工姓名
			RetireDate: null, // 退休日期
			ResignType: null, // 离职类型
			Describe: null, // 退休说明
			Approver: null, // 审批人
			ApprovalTime: null, // 审批时间
			GroupId: null, // 所属部门ID
			BillCode: null, // 单据编号
			BillStatus: null, // 单据状态
			WorkflowStatus: null, // 工作流状态
			Remark: null, // 备注
			OrgId: null, // 所属公司ID
		},
		ActionName: null, // 当前操作名称
		IsMyApprove: null, // 是否我的审批
		Remark: null, // 审批原因
	},
});

/**
 * ===== 计算属性 =====
 * 根据响应式数据动态计算衍生值
 */

/** 是否处于审核中状态 */
const isInAudit = computed(() => stateData.vmModel.Entity.WorkflowStatus === WORKFLOW_STATUS.IN_AUDIT);

/** 是否可以审批 */
const canApprove = computed(() => !!stateData.vmModel.IsMyApprove);

/**
 * ===== 工具函数 =====
 */

/** 统一的成功处理函数 - 处理操作成功后的通用逻辑 */
const handleSuccess = () => {
	ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '操作成功');
	emit('refresh'); // 通知父组件刷新数据
	loading.value = false;
	closeDialog(); // 关闭对话框
};

/** 统一的错误处理函数 - 处理API调用失败等错误情况 */
const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

/**
 * ===== 审批操作函数 =====
 */

/** 公共的审批处理函数 - 处理审批操作的通用逻辑 */
const handleApproval = (actionName: string) => {
	stateData.vmModel.ActionName = actionName;
	loading.value = true;
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			api().approve(stateData.vmModel, '').then(handleSuccess).catch(handleError);
		} else {
			loading.value = false;
		}
	});
};

/** 关闭对话框 */
const onClose = () => {
	closeDialog();
};

/** 同意审批 */
const onAgree = () => {
	other.openDialog('填写同意原因', ApproveReasonDialog, null, null, '30%', (reason: string) => {
		stateData.vmModel.Remark = reason;
		handleApproval(ACTIONS.AGREE);
	});
};

/** 拒绝审批 */
const onDeny = () => {
	other.openDialog('填写拒绝原因', ApproveReasonDialog, { isRequired: true }, null, '30%', (reason: string) => {
		stateData.vmModel.Remark = reason;
		handleApproval(ACTIONS.REJECT);
	});
};

/**
 * ===== 数据初始化函数 =====
 */

/** 初始化页面数据 - 从路由参数或组件属性中获取记录ID */
const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	const routeId = useRouter().currentRoute.value.query.id;

	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
	} else if (routeId) {
		stateData.vmModel.Entity.ID = routeId as any;
	}
};

/** 加载页面所需的所有数据 */
const loadPageData = async () => {
	// 并行加载部门数据和实体数据
	const [entityData] = await Promise.allSettled([
		api().get(stateData.vmModel.Entity.ID ?? ''), // 获取实体详情数据
	]);

	// 处理成功的结果
	if (entityData.status === 'fulfilled') other.setValue(stateData.vmModel, entityData.value);
};

/**
 * ===== 生命周期钩子 =====
 */

/** 组件挂载时执行 - 初始化页面数据 */
onMounted(async () => {
	loading.value = true;
	initializePageData(); // 初始化页面参数

	try {
		await loadPageData(); // 加载页面数据
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false; // 无论成功失败都要关闭loading
		nextTick(() => {
			setupHeaderButtons(); // 设置头部按钮
		});
	}
});

/**
 * ===== 组件通信 =====
 */

/** 定义子组件向父组件传值/事件 */
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

/** 关闭弹窗 */
const closeDialog = () => {
	emit('closeDialog');
};

/** 设置对话框头部按钮 - 根据当前状态动态配置按钮显示 */
const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.AGREE,
			type: 'primary',
			onClick: onAgree,
			visible: isInAudit.value && canApprove.value, // 只有在审核中且有审批权限时显示
		},
		{
			text: BUTTON_TEXTS.REJECT,
			type: 'danger',
			onClick: onDeny,
			visible: isInAudit.value && canApprove.value, // 只有在审核中且有审批权限时显示
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true, // 始终显示关闭按钮
		},
	];

	emit('updateHeaderButtons', headerButtons);
};
</script>
